<?php

class I18n_Message_CSV
{
	public function & load($lang, $default_lang = 'en')
	{
		$data = array();

		$dir = LANGUAGE_PATH . '/' . $lang;

		if (!is_dir($dir))
		{
			$dir = LANGUAGE_PATH . '/' . $default_lang;

			if (!is_dir($dir))
			{
				throw new Agilet_Exception('invalid dir :dir ', array(':dir' => $dir));
			}
		}

		$files = scandir($dir);

		foreach ($files as $filename)
		{
			if (!is_string($filename) or !strpos($filename, '.csv'))
			{
				continue;
			}

			$filename = $dir . '/' . $filename;

			$file = @fopen($filename, 'rb');

			if (!$file)
			{
				continue;
			}

			while (($row = fgetcsv($file, 0, ';', '"')) !== false)
			{

				if (substr($row[0], 0, 1) === '#')
				{
					continue;
				}

				if (!isset($row[1]))
				{
					continue;
				}

				if (count($row) == 2)
				{
					$data[$row[0]] = $row[1];
				}
				else
				{
					$singular = array_shift($row);
					$data[$singular] = $row;
				}
			}

			if ($file)
			{
				fclose($file);
			}
		}

		return $data;
	}

}
